import React,{useState,useEffect} from 'react';
import { Table,Modal,Button,Space,Divider } from 'antd';
import { ReloadOutlined,PlusOutlined,LoadingOutlined,FileAddOutlined,EditOutlined } from '@ant-design/icons';
import type { ColumnsType, TableProps } from 'antd/es/table';
import { req } from '@/common/methods';
import EditComponent from './edit.tsx';



const App: React.FC = (props={prt:'category'}) => {
    const columns = [
        {
          title: '惟一标识符',
          dataIndex: 'id',
          // onFilter: (value: string, record) => record.name.indexOf(value) === 0,
          // sorter: (a, b) => a.name.length - b.name.length,
          // sortDirections: ['descend'],
        },
        {
          title: '名称',
          dataIndex: 'name',
        },
        {
          title: '创建时间',
          dataIndex: 'create_time',
        },
        {
            title:'操作',
            dataIndex:'id',
            render(id,currentItem){
                return <>
                    <Space>
                        <Button type="primary" size="small" onClick={()=>editItem('edit',id,currentItem)}>编辑</Button>
                        <Button type="primary" danger size="small" onClick={() => {
                            Modal.confirm({
                                title:`删除 - [${id}]${currentItem.name}`,
                                content:<>您即将执行删除操作，请确认！<font color="red">删除后与之关联的所有表格名称都将无法正常显示，此操作不可逆，</font>确定要删除吗？</>,
                                onOk(){
                                    req(`/api/category/delete`,{id},'post').then((data) => {
                                        Modal.success({
                                            title:'删除成功',
                                            content:<>该数据已删除<br/>反馈信息:{JSON.stringify(data)}</>,
                                            onOk(){
                                                doClose();
                                            }
                                        });
                                    }).catch((errInfo)=>{
                                        Modal.error({
                                            title:'操作出错',
                                            content:<div>
                                                <span>本条数据有可能删除失败</span>
                                                <br/>
                                                <pre>{''+errInfo}</pre>
                                            </div>
                                        });
                                    })
                                },
                                
                            })
                        }}>删除</Button>
                    </Space>
                </>
            }
        }
      ];
      
      const [data,setData] = useState([]);
      const [loading,setLoading] = useState(false);
      const fetchData = () => {
          setLoading(true);
          req('/api/category/get').then(data => {
              setData(data.map(item => ({...item,key:item.id})));
          }).catch(msg => Modal.error({
              title:'错误',
              content:<>无法获取数据<br/><pre>{''+msg}</pre></>
          })).finally(() => setLoading(false));
      }
      useEffect(()=>fetchData(),[]);
      const doClose = () => {
        fetchData();  
        Modal.destroyAll();
      }

      const editItem = (ty="add",id=0,currentItem={}) => {
          const isAdd = ty === 'add';
          Modal.info({
              title:`${isAdd?'添加':'编辑'}分类 ${isAdd?'':` - [${id}]${currentItem.name || ''}`}`,
              icon:isAdd?<FileAddOutlined />:<EditOutlined />,
              content:<>
                <EditComponent ty={isAdd?'add':'edit'} id={id} currentItem={currentItem} doClose={doClose}/>
              </>,
              footer:null,
              onOk(){
                  doClose();
              }
          });
      }
    return <>
        <div style={{display:'flex',justifyContent:'flex-end'}}>
            <Space>
                <Button type="default" icon={loading?<LoadingOutlined />:<ReloadOutlined />} onClick={fetchData} disabled={loading}>重新加载</Button>
                <Button type="primary" icon={<PlusOutlined />} onClick={()=>editItem('add')}>添加分类</Button>
            </Space>
        </div>
        <Divider>{`分类管理`}</Divider>
        <Table columns={columns} dataSource={data} loading={loading} key={Math.random()}/>
    </>
}

export default App;